﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WLYT.Admin.WebApi.Models;
using WLYT.Application.Interfaces;
using WLYT.Domain.Model;

namespace WLYT.Admin.WebApi.Controllers
{
    [System.Web.Http.Description.ApiExplorerSettings(IgnoreApi = true)]
    public class SysMenuController : BaseController
    {
        private readonly ISys_MenusService Sys_MenusService;

        public SysMenuController(ISys_MenusService sys_MenusService)
        {
            Sys_MenusService = sys_MenusService;
        }

        [Route("api/menu/GetList")]
        public async Task<List<Tree>> GetList()
        {
            List<Tree> children = await RouteTreeLoad();
            List<Tree> result = new List<Tree>
            {
                new Tree
                {
                    key = "*",
                    title = "全部",
                    children = children
                }
            };
            return result;
        }

        private async Task<List<Tree>> RouteTreeLoad()
        {
            IList<Sys_Menus> menus = await Sys_MenusService.GetAll();

            IList<Sys_Menus> parentRouteData = menus.Where(r => r.MenuParentId == 0).OrderBy(m => m.Sort).ToList();

            List<Tree> routeData = new List<Tree>();

            foreach (Tree item in parentRouteData.Select(m => new Tree
            {
                title = m.MenuName,
                key = m.MenuPageUrl,
                id = m.Id,
                children = new List<Tree>()
            }))
            {
                RouteChildListLoad(item, menus);
                routeData.Add(item);
            }
            return routeData;
        }

        private void RouteChildListLoad(Tree sItem, IList<Sys_Menus> cacheRouteData)
        {
            List<Sys_Menus> childRoutes = cacheRouteData.Where(a => a.MenuParentId == sItem.id).OrderBy(s => s.Sort).ToList();
            foreach (Tree item in childRoutes.Select(m => new Tree
            {
                title = m.MenuName,
                key = m.MenuPageUrl,
                id = m.Id,
                children = new List<Tree>(),
            }))
            {
                RouteChildListLoad(item, cacheRouteData);
                sItem.children.Add(item);
            }
        }
    }
}